//
//  COLaunchView.swift
//  CocoProject
//
//  Created by Vill on 2023/11/7.
//

import UIKit
import AVFoundation

class COLaunchView: UIView {

    var launchStaticMv = ""

    lazy var videoImage: UIImageView = {
        let video = UIImageView(frame: self.frame)
        video.contentMode = .scaleAspectFill
        video.clipsToBounds = true
        return video
    }()
    
    fileprivate var playItem:AVPlayerItem{
        get{
            let launchShow = URL(string:self.launchStaticMv)!
            let playItem = AVPlayerItem(url: launchShow)
            return playItem
        }
    }
    
    fileprivate lazy var player: AVPlayer = {
        let player = AVPlayer(playerItem:playItem)
        player.volume = 0.5
        //设置播放完成后发送通知
        NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEndTimeNotification(noti:)), name: .AVPlayerItemDidPlayToEndTime, object: nil)
        return player
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        if (kStaticStartStr.keyGetNSDefaultsKey() != nil){
            let launchStatic = kStaticStartStr.keyGetNSDefaultsKey() as! String
            let staticArr = launchStatic.components(separatedBy: ",")
            self.launchStaticMv = staticArr.first!
            addSubview(videoImage)
            ///获取本地视频第5秒的截图（这个可以自己根据实际情况来定）
            videoImage.image = getVideoCurrentImage(1.0, self.launchStaticMv)
            //这里需要根据内容切换显示图片视图还是显示视频视图
            setupVideoUI()
        }
 
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    @objc private func dismiss(){
        UIView.animate(withDuration: 0.5, animations: {
            //渐隐
            self.alpha = 0
        }, completion: { Bool in
            self.removeFromSuperview()
        })
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    /// 获取视频的关键图片
    /// - Returns: 第几秒的图片
    func getVideoCurrentImage(_ second: Double,_ videoUrl: String) -> UIImage? {
        let videoStr = URL(string: videoUrl)!
        let asset = AVURLAsset(url: videoStr)
        let generator = AVAssetImageGenerator(asset: asset)
        generator.appliesPreferredTrackTransform = true
        let time = CMTimeMakeWithSeconds(0, preferredTimescale: 1)
        var actualTime: CMTime = CMTimeMake(value: 0, timescale: 0)
        do {
            let imageRef = try generator.copyCGImage(at: time, actualTime: &actualTime)
            let image = UIImage(cgImage: imageRef)
            // Use the `image` as you like
            return image
        } catch {
            print("Failed to generate image: \(error)")
            return nil
        }
    }

    fileprivate func setupVideoUI(){
        backgroundColor = .clear
        NotificationCenter.default.addObserver(self, selector: #selector(playVideos), name: NSNotification.Name(rawValue: "appBecomeActive"), object: nil)
        setupForAVplayerView()
        player.play()
    }
    
    private func setupForAVplayerView(){
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = bounds
        playerLayer.videoGravity = .resizeAspectFill
        layer.addSublayer(playerLayer)
    }
    
    @objc private func playerItemDidPlayToEndTimeNotification(noti:Notification){
        player.seek(to: CMTime(value: 0, timescale: 1))
        player.play()
    }
    
    @objc private func playVideos(){
        player.play()
    }
}
